package com.blog.blog.controller;

import com.blog.blog.common.ApiBaseResponse;
import com.blog.blog.common.PageResponse;
import com.blog.blog.vo.CommentAdminVO;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/comments")
public class AdminCommentController {

    private final JdbcTemplate jdbcTemplate;

    public AdminCommentController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @GetMapping
    @com.blog.blog.util.annotations.RequirePerm({"comment:manage"})
    public ApiBaseResponse<PageResponse<CommentAdminVO>> page(@RequestParam Integer pageNo,
                                                              @RequestParam Integer pageSize,
                                                              @RequestParam(required = false) Integer status,
                                                              @RequestParam(required = false) Long articleId) {
        int p = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        int s = (pageSize == null || pageSize < 1) ? 10 : Math.min(pageSize, 200);
        int offset = (p - 1) * s;
        String where = " WHERE 1=1" + (status != null ? " AND status = " + status : "") + (articleId != null ? " AND article_id = " + articleId : "");
        Long total = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM blog_comment" + where, Long.class);
        List<CommentAdminVO> records = jdbcTemplate.query(
                "SELECT id, article_id AS articleId, parent_id AS parentId, content, nickname, email, status, create_time AS createTime " +
                        "FROM blog_comment" + where + " ORDER BY create_time DESC LIMIT ? OFFSET ?",
                new BeanPropertyRowMapper<>(CommentAdminVO.class), s, offset);
        return ApiBaseResponse.success(new PageResponse<>(total == null ? 0 : total, records));
    }

    @DeleteMapping("/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"comment:manage"})
    public ApiBaseResponse<Boolean> delete(@PathVariable Long id) {
        int n = jdbcTemplate.update("DELETE FROM blog_comment WHERE id = ?", id);
        return ApiBaseResponse.success(n > 0);
    }

    @PutMapping("/{id}/approve")
    @com.blog.blog.util.annotations.RequirePerm({"comment:manage"})
    public ApiBaseResponse<Boolean> approve(@PathVariable Long id) {
        int n = jdbcTemplate.update("UPDATE blog_comment SET status = 1 WHERE id = ?", id);
        return ApiBaseResponse.success(n > 0);
    }

    @PutMapping("/{id}/reject")
    @com.blog.blog.util.annotations.RequirePerm({"comment:manage"})
    public ApiBaseResponse<Boolean> reject(@PathVariable Long id) {
        int n = jdbcTemplate.update("UPDATE blog_comment SET status = 2 WHERE id = ?", id);
        return ApiBaseResponse.success(n > 0);
    }
}


